package com.luo.stock.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.luo.stock.service.StockService;
import com.luo.stock.vo.resp.PageResult;
import com.luohai.stock.mapper.StockBusinessMapper;
import com.luohai.stock.mapper.StockMarketIndexInfoMapper;
import com.luohai.stock.mapper.StockOuterMarketIndexInfoMapper;
import com.luohai.stock.mapper.StockRtInfoMapper;
import com.luohai.stock.pojo.domain.*;
import com.luohai.stock.pojo.entity.StockBusiness;
import com.luohai.stock.pojo.vo.R;
import com.luohai.stock.pojo.vo.ResponseCode;
import com.luohai.stock.pojo.domain.StockInfoConfig;
import com.luohai.stock.pojo.vo.stockOuterMarketVo;
import com.luohai.stock.utils.DateTimeUtil;
//import com.sun.deploy.net.URLEncoder;
//import com.sun.deploy.net.URLEncoder;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Description
 * @Author 奥观海
 * @Date 2024/9/16
 */
@Service
@Slf4j
public class StockServiceImpl implements StockService {
    @Autowired
    private StockInfoConfig stockInfoConfig;
    @Autowired
    private StockMarketIndexInfoMapper stockMarketIndexInfoMapper;
    @Autowired
    private StockRtInfoMapper stockRtInfoMapper;
    @Autowired
    private Cache<String,Object> cache;
    @Autowired
    private StockOuterMarketIndexInfoMapper stockOuterMarketIndexInfoMapper;
    @Autowired
    private StockBusinessMapper stockBusinessMapper;
    @Override
    public R<List<InnerMarketDomain>> getIndexAll() {
            List<String> inner = stockInfoConfig.getInner();
            Date lastDate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
            //lastDate=DateTime.parse("2021-12-28 09:31:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
            List<InnerMarketDomain> list = stockMarketIndexInfoMapper.getIndexAll(lastDate, inner);
        if(CollectionUtils.isEmpty(list)){
      return R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        return R.ok(list);
    }

    @Override
    public R<List<StockBlockDomain>> getSectorAll() {
            Date lastDate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
    //   lastDate=DateTime.parse("2021-12-21 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
            List<StockBlockDomain> list=stockMarketIndexInfoMapper.getSectorAll(lastDate);
   if(CollectionUtils.isEmpty(list)){
            return R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        return R.ok(list);
    }

    @Override
    public R<PageResult<StockUpdownDomain>> getStockPage(Integer page, Integer pageSize) {

          Date lastdate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
         // lastdate=DateTime.parse("2021-12-30 09:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
          List<StockUpdownDomain> list=stockRtInfoMapper.getStockPage(lastdate);
          if(CollectionUtil.isEmpty(list)){
              return R.error(ResponseCode.NO_RESPONSE_DATA);
          }
        int start=(page-1)*pageSize;
        int end=page*pageSize;
        int size = list.size();
       List<StockUpdownDomain> dominList=new ArrayList<>();
        for(;start<end;start++){
            if(start==size){
                break;
            }
            dominList.add(list.get(start));
        }
        int pSize=pageSize;
        if(start==size){
        pSize=size%pageSize;
        }
//        PageHelper.startPage(page,pageSize);
//        Date lastdate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
//        lastdate=DateTime.parse("2022-06-07 15:00:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
//        List<StockUpdownDomain> list=stockRtInfoMapper.getStockPage(lastdate);
//        if(CollectionUtil.isEmpty(list)){
//            return R.error(ResponseCode.NO_RESPONSE_DATA);
//        }

        int totalPages=0;
        if(size%pageSize!=0){
            totalPages=size/pageSize+1;
        }else {
            totalPages=size/pageSize;
        }
        PageResult<StockUpdownDomain> result=new PageResult<>();
  result.setTotalRows((long) size);
  result.setTotalPages(totalPages);
  result.setPageNum(page);
  result.setPageSize(pageSize);
  result.setSize(pSize);
  result.setRows(dominList);
        return R.ok(result);
    }

    @Override
    public R<List<StockUpdownDomain>> getStock4Increase() {
        Date lastDate = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();

    //    lastDate=DateTime.parse("2021-12-30 09:42:00",DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       List<StockUpdownDomain> list= stockRtInfoMapper.getStock4Increase(lastDate);
      if(CollectionUtil.isEmpty(list)){
          return R.error(ResponseCode.NO_RESPONSE_DATA);
      }
        return R.ok(list);
    }

    @Override
    public void stockExport(Integer page, Integer pageSize, HttpServletResponse response) {
        try {
            R<PageResult<StockUpdownDomain>> stockPage = this.getStockPage(page, pageSize);
            List<StockUpdownDomain> infos = stockPage.getData().getRows();
            if (CollectionUtils.isEmpty(infos)) {
                //响应提示信息
                R<Object> r = R.error(ResponseCode.NO_RESPONSE_DATA);
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().write(new ObjectMapper().writeValueAsString(r));
                return;
            }
            //设置响应excel文件格式类型
            response.setContentType("application/vnd.ms-excel");
            //2.设置响应数据的编码格式
            response.setCharacterEncoding("utf-8");
            //3.设置默认的文件名称
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("stockRt", "UTF-8");
            //设置默认文件名称：兼容一些特殊浏览器
            response.setHeader("content-disposition", "attachment;filename=" + fileName + ".xlsx");
            //4.响应excel流
            EasyExcel
                    .write(response.getOutputStream(),StockUpdownDomain.class)
                    .sheet("股票信息")
                    .doWrite(infos);
        } catch (IOException e) {
            e.printStackTrace();
            log.info("当前导出数据异常，当前页：{},每页大小：{},异常信息：{}",page,pageSize,e.getMessage());
        }
    }

    @Override
    public R<Map<String, List>> getTradeAmt() {
        DateTime lastDate4Stock = DateTimeUtil.getLastDate4Stock(DateTime.now());
        DateTime openDate = DateTimeUtil.getOpenDate(lastDate4Stock);
        Date startTime4T = lastDate4Stock.toDate();
        Date endTime4T = openDate.toDate();
        List<String> inner = stockInfoConfig.getInner();
     //   startTime4T=DateTime.parse("2022-01-03 14:40:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
      //  endTime4T=DateTime.parse("2022-01-03 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       List<Map> amtList= stockMarketIndexInfoMapper.getTradeAmt(startTime4T,endTime4T,inner);
       if(CollectionUtils.isEmpty(amtList)){
           return R.error(ResponseCode.NO_RESPONSE_DATA);
       }
        DateTime  lastDate4StockPre = DateTimeUtil.getLastDate4Stock(DateTime.now().minusDays(1));
        DateTime  openDatePre = DateTimeUtil.getOpenDate(lastDate4Stock);
        Date startTime4PreT = lastDate4StockPre.toDate();
        Date endTime4PreT = openDatePre.toDate();
     //   endTime4PreT=DateTime.parse("2022-01-02 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       // startTime4PreT=DateTime.parse("2022-01-02 14:40:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<Map>  yesAmtList=stockMarketIndexInfoMapper.getTradeAmt(startTime4PreT,endTime4PreT,inner);
        if(CollectionUtils.isEmpty(yesAmtList)){
            return R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        Map<String,List> map=new HashMap<>();
        map.put("amtList",amtList);
        map.put("yesAmtList",yesAmtList);
        return R.ok(map);
    }

    @Override
    public R<Map> getStockeUpdown() {
        Date lastDate4Stock = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
    //    lastDate4Stock=DateTime.parse("2022-01-06 09:55:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<String> upDownRange = stockInfoConfig.getUpDownRange();
        List<Map> list=stockRtInfoMapper.getStockeUpdown(lastDate4Stock);
        List<Map<String, Object>> mapList=new ArrayList<>();
        for (String s : upDownRange) {
            Object m=0;
            for (Map map : list) {
                if (map.get("title").equals(s)) {
                   m=  map.get("count");
                   break;
                }
            }
            Map<String,Object> map=new HashMap<>();
            map.put("title",s);
            map.put("count",m);
            mapList.add(map);
        }
        if(CollectionUtil.isEmpty(list)){
            return R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("time",lastDate4Stock);
        map.put("infos",mapList);
        return R.ok(map);
    }

    @Override
    public R<Map> getStockUpdownCount() {
        DateTime lastDate4Stock = DateTimeUtil.getLastDate4Stock(DateTime.now());
        DateTime openDate = DateTimeUtil.getOpenDate(lastDate4Stock);
        Date startTime4T = lastDate4Stock.toDate();
        Date endTime4T = openDate.toDate();
      //  startTime4T=DateTime.parse("2022-01-06 14:25:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       // endTime4T=DateTime.parse("2022-01-06 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<Map> upList=stockRtInfoMapper.getStockUpdownCount(startTime4T,endTime4T,1);
        List<Map> downList=stockRtInfoMapper.getStockUpdownCount(startTime4T,endTime4T,0);
        Map<String, List<Map>> map=new HashMap<>();
        map.put("upList",upList);
        map.put("downList",downList);
        return R.ok(map);
    }

    @Override
    public R<List<Stock4MinuteDomain>> getTimeSharing(String code) {
        DateTime endDate = DateTimeUtil.getLastDate4Stock(DateTime.now());
        DateTime startDate = DateTimeUtil.getOpenDate(endDate);
        Date startTime4T = startDate.toDate();
        Date endTime4T = endDate.toDate();
     //   startTime4T=DateTime.parse("2021-12-30 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
      //  endTime4T=DateTime.parse("2021-12-30 14:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<Stock4MinuteDomain> list=stockRtInfoMapper.getTimeSharing(code,startTime4T,endTime4T);
        if(CollectionUtils.isEmpty(list)){
            return R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        return R.ok(list);
    }

    @Override
    public R<List<Stock4EvrDayDomain>> getDkline(String code) {
        DateTime endDate = DateTimeUtil.getLastDate4Stock(DateTime.now());
        DateTime startDate=endDate;
        for(int i=0;i<5;i++){
            startDate= DateTimeUtil.getPreviousTradingDay(startDate);
        }
        Date startTime4T = startDate.toDate();
        Date endTime4T = endDate.toDate();
      //  startTime4T=DateTime.parse("2022-01-01 09:30:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
      //  endTime4T=DateTime.parse("2022-01-06 14:25:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        //List<Stock4EvrDayDomain> list=stockRtInfoMapper.getDkline(code,startTime4T,endTime4T);
       List<Date> closeDate=stockRtInfoMapper.getMaxDate(code,startTime4T,endTime4T);
        List<Stock4EvrDayDomain> list=stockRtInfoMapper.getDklineAndMaxDate(code,closeDate);
        if(CollectionUtils.isEmpty(list)){
            return R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        return R.ok(list);
    }

    @Override
    public R<List<stockOuterMarketVo>> getOuterMarket() {

       Date lastDate4Stock = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
    //   lastDate4Stock=DateTime.parse("2022-05-18 15:58:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       List<stockOuterMarketVo> list= stockOuterMarketIndexInfoMapper.getOuterMarket(lastDate4Stock);

   if(CollectionUtils.isEmpty(list)){
       return R.error(ResponseCode.NO_RESPONSE_DATA);
   }
   return R.ok(list);
    }

    @Override
    public R<List<Map>> getSearch(String searchStr) {
        searchStr='%'+searchStr+'%';
        List<Map> list=stockBusinessMapper.getSearch(searchStr);
        if(CollectionUtils.isEmpty(list))
        {
            R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        return R.ok(list);
    }

    @Override
    public R<StockBusinessDomain> getDescribe(String code) {
        StockBusinessDomain stockBusiness= stockBusinessMapper.getDescribe(code);
       if(stockBusiness==null){
           return R.error(ResponseCode.NO_RESPONSE_DATA);
       }
        return R.ok(stockBusiness);
    }

    @Override
    public R<List<InnerStockWeekDomain>> getWeekkline(String code) {
        DateTime endDate = DateTimeUtil.getLastDate4Stock(DateTime.now());
        DateTime startDate = DateTimeUtil.getMonthDate(endDate);
        Date startTime4T = startDate.toDate();
        Date endTime4T = endDate.toDate();
      //  startTime4T=DateTime.parse("2022-1-1 09:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       // endTime4T=DateTime.parse("2022-1-30 09:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<InnerStockWeekDomain> innerStockWeekDomain=stockBusinessMapper.getWeekkline1(code,startTime4T,endTime4T);
        List<BigDecimal> openPrices=stockBusinessMapper.getWeekkline2(code,startTime4T,endTime4T);
        List<BigDecimal> closePrices=stockBusinessMapper.getWeekkline3(code,startTime4T,endTime4T);
        int tem=0;
        for (InnerStockWeekDomain stockWeekDomain : innerStockWeekDomain) {
            BigDecimal op = openPrices.get(0);
            BigDecimal cl = closePrices.get(0);
            stockWeekDomain.setOpenPrice(op);
            stockWeekDomain.setClosePrice(cl);
            stockWeekDomain.setStockCode(code);
            tem++;
        }
        return R.ok(innerStockWeekDomain);
    }

    @Override
    public R<InnerStockDomain> getSecondDetail(String code) {
        Date lastDate4Stock = DateTimeUtil.getLastDate4Stock(DateTime.now()).toDate();
    //    lastDate4Stock=DateTime.parse("2021-12-30 09:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       InnerStockDomain stockDomain= stockRtInfoMapper.getSecondDetail(code,lastDate4Stock);
        if (stockDomain == null) {
            return R.error(ResponseCode.NO_RESPONSE_DATA);
        }
        return R.ok(stockDomain);
    }

    @Override
    public R<List<StockWaterDomain>> getscreenSecond(String code) {
        DateTime endDate = DateTimeUtil.getLastDate4Stock(DateTime.now());
        DateTime startDate = DateTimeUtil.getMonthDate(endDate);
        Date startTime4T = startDate.toDate();
        Date endTime4T = endDate.toDate();
      //  startTime4T=DateTime.parse("2021-12-30 09:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
       // endTime4T=DateTime.parse("2021-12-30 15:32:00", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")).toDate();
        List<StockWaterDomain> list= stockRtInfoMapper.getscreenSecond(code,startTime4T,endTime4T);
  if(CollectionUtils.isEmpty(list)){
      return R.error(ResponseCode.NO_RESPONSE_DATA);
  }
        return R.ok(list);
    }
}
